#include <iostream>
#include <string>
#include <cstdio>
#include <unistd.h>
#include <cstring>
#include <pthread.h>

using namespace std;

// 添加__thread,可以将一个内置类型设置为线性局部存储 -> 给每个线程一份

string changeId(const pthread_t &thread_id)
{
    char tid[128];
    snprintf(tid, sizeof(tid), "0x%x", thread_id);
    return tid;
}

void *start_routine(void *args)
{
    string threadname = static_cast<const char*>(args);
    // pthread_detach(pthread_self());// 设置自己为分离状态
    int cnt = 5;
    while(cnt--)
    {
       
        cout << threadname << " running..." << changeId(pthread_self()) << endl;
        sleep(1);
    }

    return nullptr;
}

int main()
{
    pthread_t tid;
    pthread_create(&tid, nullptr, start_routine, (void*)"thread 1");
    string main_id = changeId(pthread_self());
    pthread_detach(tid);

    cout << "main thread running ... new thread id: " << changeId(tid) << "main thread id: " << main_id << endl;

    // 一个线程默认是joinable的,如果设置了分离状态,不能够进行等待了
    // int n = pthread_join(tid, nullptr);
    // cout << "result: " << n << " : " << strerror(n) << endl;

    while(true)
    {
        cout << "main thread running ... new thread id: " << changeId(tid) << "main thread id: " << main_id << endl;
        sleep(1);
    }
    return 0;
}